import React, { useState, useEffect } from 'react';
import { Card } from '../../components/Card';
import { audioManager } from '../../utils/audio/audioManager';
import { useChromeStorage } from '../../hooks/useChromeStorage';
import './BackgroundNoiseSection.css';

const noiseTypes = [
  { id: 'rain', name: 'Rain', icon: '🌧️', description: 'Gentle rainfall' },
  { id: 'ocean', name: 'Ocean', icon: '🌊', description: 'Waves on the beach' },
  { id: 'forest', name: 'Forest', icon: '🌲', description: 'Nature sounds' },
  { id: 'fireplace', name: 'Fireplace', icon: '🔥', description: 'Crackling fire' },
  { id: 'white-noise', name: 'White Noise', icon: '📻', description: 'Steady background' },
  { id: 'wind', name: 'Wind', icon: '💨', description: 'Gentle breeze' },
  { id: 'cafe', name: 'Cafe', icon: '☕', description: 'Ambient chatter' },
  { id: 'thunder', name: 'Thunder', icon: '⛈️', description: 'Distant storm' }
];

export const BackgroundNoiseSection = () => {
  const [noiseSettings, setNoiseSettings] = useState({ volume: 0.5, playing: null });
  const [currentPlaying, setCurrentPlaying] = useState(null);

  useEffect(() => {
    loadSettings();
  }, []);

  const loadSettings = async () => {
    chrome.storage.local.get(['noiseSettings'], (result) => {
      const settings = result.noiseSettings || { volume: 0.5, playing: null };
      setNoiseSettings(settings);
      setCurrentPlaying(settings.playing);
      if (settings.playing) {
        audioManager.playAmbientSound(settings.playing, settings.volume);
      }
    });
  };

  const handlePlay = async (noiseId) => {
    if (currentPlaying === noiseId) {
      audioManager.stopAmbientSound();
      setCurrentPlaying(null);
      await chrome.storage.local.set({ noiseSettings: { ...noiseSettings, playing: null } });
    } else {
      if (currentPlaying) {
        audioManager.stopAmbientSound();
      }
      await audioManager.playAmbientSound(noiseId, noiseSettings.volume);
      setCurrentPlaying(noiseId);
      await chrome.storage.local.set({ noiseSettings: { ...noiseSettings, playing: noiseId } });
    }
  };

  const handleVolumeChange = async (e) => {
    const volume = parseFloat(e.target.value) / 100;
    audioManager.setVolume(volume);
    const newSettings = { ...noiseSettings, volume };
    setNoiseSettings(newSettings);
    await chrome.storage.local.set({ noiseSettings: newSettings });
  };

  return (
    <section className="background-noise-section">
      <div className="section-header">
        <h2>Background Noise</h2>
        <p style={{ color: 'var(--text-secondary)', fontSize: '14px', marginTop: '5px' }}>
          Relaxing sounds for wind down and break time
        </p>
      </div>

      <div className="noise-controls">
        <div className="noise-control-item">
          <label>Volume</label>
          <div className="volume-control">
            <input
              type="range"
              min="0"
              max="100"
              value={noiseSettings.volume * 100}
              onChange={handleVolumeChange}
              className="volume-slider"
            />
            <span>{Math.round(noiseSettings.volume * 100)}%</span>
          </div>
        </div>
      </div>

      <div className="noise-grid">
        {noiseTypes.map((noise) => (
          <Card
            key={noise.id}
            className={`noise-card ${currentPlaying === noise.id ? 'playing' : ''}`}
          >
            <div className="noise-icon">{noise.icon}</div>
            <div className="noise-title">{noise.name}</div>
            <div className="noise-description">{noise.description}</div>
            <button
              className="noise-play-btn"
              onClick={() => handlePlay(noise.id)}
            >
              {currentPlaying === noise.id ? '⏸' : '▶'}
            </button>
          </Card>
        ))}
      </div>
    </section>
  );
};

